<?php

/**
 * This class is for create,read,update,delete of user groups
 * @author Aimon 2015.02.18
 */
class UserGroupController extends BaseController {

	// Table
	public $table = 'user_group';

	// Eloquent Model
	public $model = 'UserGroup';

	// Base Route
	public $base = 'user-group';

	// Localization
	public $local = 'en';

	// Language Name
	public $language = 'user_group';

	// Breadcrumbs
	public $breadcrumbs = [ ['link' => 'user-group' , 'title' => 'User Group'] ];

	// Set List Data - Input, Object
	public function setListData( $data, $object ) {
		
		// Filter by user group name
		if( !empty($data['filter_name']) ) {
			$object = $object->where('name', 'LIKE', '%' . $data['filter_name'] . '%');
		}
		
		return $object;
	}

	public function addFormData( $data, $id = NULL) {

		// Get Supply Chain Management's User Levels
		$data['levels'] = Constant::getUserLevels();
		
		// Get All Modules
		$data['modules'] = Permission::getAll($id);
 		return $data;
	}

	public function addShowData( $data, $id = NULL)  {
		
		// Get All Modules
		$data['modules'] = Permission::getAll($data->id);
		
		return $data;		
	}
	
	// Process before storing data
	public function preStore( $data ) {

		// Updated At Rules
		$this->rules['name'] = 'required';

		return $data;
	}

	public function postStore( $data, $object ) {

		UserPermission::where('USER_GROUP_id', '=', $object->id)->delete();

		foreach( $data['user_permission'] as $user_permission ) {

			$data = array(
					'USER_GROUP_id'	=> $object->id,
					'route' => $user_permission['route'],
					'title' => $user_permission['title'],
					//'icon' 	=> $user_permission['icon'],
					'create'=> !empty($user_permission['create']),
					'read'	=> !empty($user_permission['read']),
					'update'=> !empty($user_permission['update']),
					'delete'=> !empty($user_permission['delete']),				
				);

			UserPermission::insert($data);

		}

		return $data;
	}

	// Process before updating data
	public function preUpdate( $data ) {
		
		// Unset existing permissions
		Cache::forget('permission_' . $data['id']);

		// Updated At Rules
		$this->rules['name'] = 'required';
		
		return $data;
	}

	public function postUpdate( $data, $object ) {			

		UserPermission::where('USER_GROUP_id', '=', $object->id)->delete();

		foreach( $data['user_permission'] as $user_permission ) {

			$data = array(
					'USER_GROUP_id' => $object->id,
					'route' => $user_permission['route'],
					'title' => $user_permission['title'],
					//'icon' 	=> $user_permission['icon'],
					'create'=> !empty($user_permission['create']),
					'read'	=> !empty($user_permission['read']),
					'update'=> !empty($user_permission['update']),
					'delete'=> !empty($user_permission['delete']),					
				);

			UserPermission::insert($data);

		}

		return $data;
	}


}